package com.itheima.app.controller;

import com.itheima.app.manager.UserManager;
import com.itheima.domain.db.User;
import com.itheima.vo.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@RestController
public class UserController {
    @Autowired
    private UserManager userManager;

    @PostMapping("/user/save")
    public ResponseEntity save(@RequestBody User user){
       return userManager.save(user);
    }

    @GetMapping("/user/findByPhone")
    public ResponseEntity findByPhone(String phone) {
        return userManager.findByPhone(phone);
    }

    //发送短信
    @PostMapping("/user/login")
    public void sendSms(@RequestBody Map<String, String> param) {
        //1.接受请求参数
        String phone = param.get("phone");
        //2.调用manager
        userManager.sendSms(phone);
    }

    //验证验证码
    @PostMapping("/user/loginVerification")
    public ResponseEntity regAndLogin(@RequestBody Map<String,String> param){
        //接收求情参数
        String phone = param.get("phone");
        String verificationCode = param.get("verificationCode");
        //调用manage
      return  userManager.regAndLogin(phone,verificationCode);
    }

    //完善用户信息
    @PostMapping("/user/loginReginfo")
    public void saveUserInfo(@RequestBody UserInfo userInfo, @RequestHeader("Authorization") String token) {
        userManager.saveUserInfo(userInfo, token);
    }

    //添加用户头像
    @PostMapping({"/user/loginReginfo/head","/users/header"})
    public ResponseEntity saveHeadPhoto(MultipartFile headPhoto, @RequestHeader("Authorization") String token) throws IOException {
       return userManager.saveHeadPhoto(headPhoto, token);
    }

    //查询用户信息
    @GetMapping("/users")
    public ResponseEntity findByUserInfoVo(Long userID, @RequestHeader("Authorization") String token) {
        if (userID != null) {
            return userManager.findByUserInfoVo(userID);
        } else {
            User user = userManager.findByToken(token);
           return userManager.findByUserInfoVo(user.getId());
        }
    }
    //修改用户信息
    @PutMapping("/users")
    public void updateUserInfo(@RequestBody UserInfo userInfo, @RequestHeader("Authorization") String token) {
        userManager.updateUserInfo(userInfo,token);
    }




}
